package com.ruoyi.business.utils;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class ChuanShanJiaSignUtil {
    public static class Req {
        String appID;
        String signType;
        String version;
        long timestamp;
        String reqID;
        String data;
        String sign;

        public Req(String appID, String signType, long timestamp, String reqID, String data) {
            this.appID = appID;
            this.signType = signType;
            this.timestamp = timestamp;
            this.reqID = reqID;
            this.data = data;
        }
    }

    static String md5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5 = md.digest(data.getBytes(StandardCharsets.UTF_8));

            StringBuilder sb = new StringBuilder();
            for (byte b : md5) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw null;
        }
    }

    public static String getSign(Req req) {
//        final String secureKey = "3876803d823b468bc59dfa7ccc1b6ead";
        final String secureKey = "Jji_qhAp_PC8_jAKVj34p27iZMxCedTirW6fSBZ6ZwU=";
        String signStr = String.format("app_id=%s&data=%s&req_id=%s&timestamp=%d%s", req.appID, req.data,
                req.reqID, req.timestamp, secureKey);
        return md5(signStr);
    }

    public static void main(String[] args) {
        String data = "{\n            \"cursor\": 0,\n            \"count\": 0,\n            \"sort_by\": 1,\n            \"order_by\": 2,\n            \"city_code\": \"652900\",\n            \"longitude\": 116.4304499308579,\n            \"latitude\": 39.97088882475504,\n            \"distance_max\": 1000,\n            \"category_id\": 0,\n            \"keyword\": \"\"\n        }";
        Req req = new Req("5529383", "MD5", 1714297546, "9ad00327-c006-40dc-b8bf-ffc52b1cdfb6", data);
        req.sign = getSign(req);
        System.out.printf("sign: %s\n", req.sign);
        // serialize req to json
    }
}
